# !/usr/bin/env python3
# -*- coding: utf-8 -*-
# @Time    : 2024/11/8 16:05
# @Author  : lsy
# @FileName: app.py
# @Software: PyCharm
# @Function: https://pic.netbian.com/
"""
实现逻辑：
    连接MongoDB获取图片信息
    下载或者设置壁纸
    选择类型，设置随机壁纸
框架：beeware
"""
import asyncio
import ctypes
import subprocess
import time
import platform
import os
import winreg
from pathlib import Path

import toga
from toga.style.pack import *
from pymongo import MongoClient
from motor.motor_asyncio import AsyncIOMotorClient

# 创建异步客户端
uri = 'mongodb://readonlyuser:readonlBeeWallpaper@121.40.91.123:7758/?authSource=BeeWallpaper'
async_client = AsyncIOMotorClient(uri)
async_db = async_client.BeeWallpaper  # 获取数据库对象

# 完整的图像集合
async_collection = async_db.BeeWallpaper_content
# 缩略的图像集合
async_collection_thumbnail = async_db.BeeWallpaper_thumbnail_content  # 获取集合对象

# 常规创建客户端
client = MongoClient('121.40.91.123', 7758,
                     username='readonlyuser',
                     password='readonlBeeWallpaper',
                     authSource='BeeWallpaper')
# 连接到特定的数据库（如果数据库不存在，它将在第一次插入数据时创建）
db = client['BeeWallpaper']
# 连接到特定的集合（如果集合不存在，它将在第一次插入数据时创建）
collection = db['BeeWallpaper_content']
collection_thumbnail = db['BeeWallpaper_thumbnail_content']


class BeeWallpaper(toga.App):
    def startup(self):
        self.main_box = toga.Box(style=Pack(direction=COLUMN, flex=1))
        self.page = 1
        # 搜索页面的数量和总数 占位
        self.search_page = 1
        self.search_page_total = 10
        self.search_value = ''
        # 固定总页数
        self.image_total = 100

        # 加载中页面
        self.loading_box = toga.Box(style=Pack(direction=COLUMN, flex=1))
        self.progress = toga.ProgressBar(max=12, value=1)
        self.loading_box.add(self.progress)
        self.progress.start()

        self.main_window = toga.MainWindow(title=self.formal_name)
        self.main_window.icon = 'resources/icon.ico'
        self.main_window.content = self.loading_box
        self.main_window.show()
        # 异步加载数据
        asyncio.create_task(self.load_data())

    async def load_data(self):
        query = {}
        uri = 'mongodb://readonlyuser:readonlBeeWallpaper@121.40.91.123:7758/BeeWallpaper'
        async_client = AsyncIOMotorClient(uri)
        async_db = async_client.BeeWallpaper  # 获取数据库对象
        # 缩略的图像集合
        async_collection_thumbnail = async_db.BeeWallpaper_thumbnail_content  # 获取集合对象
        load_data_res = async_collection_thumbnail.find(query).sort("_id", -1).skip(12 * (self.page - 1)).limit(12)
        self.result = []
        async for doc in load_data_res:
            self.result.append(doc)
        async_client.close()
        # 测试获取到的数据
        # print(self.result[0].get('name'))
        # 搜索框 padding=(上、右、下、左)
        self.search_input = toga.TextInput(placeholder='搜索请用英文,比如:red ',
                                           style=Pack(flex=1, padding=(0, 0, 0, 130), width=150))
        self.search_button = toga.Button(
            "🔍",
            on_press=self.search,
            style=Pack(flex=1, width=35, padding=(0, 50, 0, 0))
        )
        title_box = toga.Box(style=Pack(direction=ROW, width=400, padding=(10, 50, 10, 100)))
        title_box.add(self.search_input)
        title_box.add(self.search_button)

        # 内容框
        self.content_one_box = toga.Box(style=Pack(flex=1, direction=ROW, padding=(0, 5, 0, 5), height=140))
        self.content_two_box = toga.Box(style=Pack(flex=1, direction=ROW, padding=(15, 5, 0, 5), height=140))
        self.content_three_box = toga.Box(style=Pack(flex=1, direction=ROW, padding=(15, 5, 0, 5), height=140))
        self.content_four_box = toga.Box(style=Pack(flex=1, direction=ROW, padding=(15, 5, 0, 5), height=140))

        # 第一部分
        self.image_1 = toga.Image(src=self.result[0].get('thumbnail_content'))
        self.view_1 = toga.ImageView(self.image_1, style=Pack(width=200, height=140, padding=(0, 5, 0, 5)))
        self.button_name_1 = self.result[0].get("image_favorites") + "  " + self.result[0].get(
            'image_scale') + " " * 10 + self.result[0].get('name')

        self.image_2 = toga.Image(src=self.result[1].get('thumbnail_content'))
        self.view_2 = toga.ImageView(self.image_2, style=Pack(width=200, height=140, padding=(0, 5, 0, 5)))
        self.button_name_2 = self.result[1].get("image_favorites") + "  " + self.result[1].get(
            'image_scale') + " " * 10 + self.result[1].get('name')

        self.image_3 = toga.Image(src=self.result[2].get('thumbnail_content'))
        self.view_3 = toga.ImageView(self.image_3, style=Pack(width=200, height=140, padding=(0, 5, 0, 5)))
        self.button_name_3 = self.result[2].get("image_favorites") + "  " + self.result[2].get(
            'image_scale') + " " * 10 + self.result[2].get('name')

        self.button_one_box = toga.Box(style=Pack(flex=1, direction=ROW, height=11, padding=(0, 5, 0, 5)))
        self.button_1 = toga.Button(self.button_name_1, on_press=self.view_details,
                                    style=Pack(background_color="rgb(204,229,255)", width=200, height=25,
                                               padding=(0, 5, 0, 5)))
        self.button_2 = toga.Button(self.button_name_2, on_press=self.view_details,
                                    style=Pack(background_color="rgb(204,229,255)", width=200, height=25,
                                               padding=(0, 5, 0, 5)))
        self.button_3 = toga.Button(self.button_name_3, on_press=self.view_details,
                                    style=Pack(background_color="rgb(204,229,255)", width=200, height=25,
                                               padding=(0, 5, 0, 5)))

        self.content_one_box.add(self.view_1)
        self.content_one_box.add(self.view_2)
        self.content_one_box.add(self.view_3)
        self.button_one_box.add(self.button_1)
        self.button_one_box.add(self.button_2)
        self.button_one_box.add(self.button_3)

        # 第二部分
        self.image_4 = toga.Image(src=self.result[3].get('thumbnail_content'))
        self.view_4 = toga.ImageView(self.image_4, style=Pack(width=200, height=140, padding=(0, 5, 0, 5)))
        self.button_name_4 = self.result[3].get("image_favorites") + "  " + self.result[3].get(
            'image_scale') + " " * 10 + self.result[3].get('name')

        self.image_5 = toga.Image(src=self.result[4].get('thumbnail_content'))
        self.view_5 = toga.ImageView(self.image_5, style=Pack(width=200, height=140, padding=(0, 5, 0, 5)))
        self.button_name_5 = self.result[4].get("image_favorites") + "  " + self.result[4].get(
            'image_scale') + " " * 10 + self.result[4].get('name')

        self.image_6 = toga.Image(src=self.result[5].get('thumbnail_content'))
        self.view_6 = toga.ImageView(self.image_6, style=Pack(width=200, height=140, padding=(0, 5, 0, 5)))
        self.button_name_6 = self.result[5].get("image_favorites") + "  " + self.result[5].get(
            'image_scale') + " " * 10 + self.result[5].get('name')

        self.button_two_box = toga.Box(style=Pack(flex=1, direction=ROW, height=11, padding=(0, 5, 0, 5)))
        self.button_4 = toga.Button(self.button_name_4, on_press=self.view_details,
                                    style=Pack(background_color="rgb(204,229,255)", width=200, height=25,
                                               padding=(0, 5, 0, 5)))
        self.button_5 = toga.Button(self.button_name_5, on_press=self.view_details,
                                    style=Pack(background_color="rgb(204,229,255)", width=200, height=25,
                                               padding=(0, 5, 0, 5)))
        self.button_6 = toga.Button(self.button_name_6, on_press=self.view_details,
                                    style=Pack(background_color="rgb(204,229,255)", width=200, height=25,
                                               padding=(0, 5, 0, 5)))

        self.content_two_box.add(self.view_4)
        self.content_two_box.add(self.view_5)
        self.content_two_box.add(self.view_6)
        self.button_two_box.add(self.button_4)
        self.button_two_box.add(self.button_5)
        self.button_two_box.add(self.button_6)

        # 第三部分
        self.image_7 = toga.Image(src=self.result[6].get('thumbnail_content'))
        self.view_7 = toga.ImageView(self.image_7, style=Pack(width=200, height=140, padding=(0, 5, 0, 5)))
        self.button_name_7 = self.result[6].get("image_favorites") + "  " + self.result[6].get(
            'image_scale') + " " * 10 + self.result[6].get('name')

        self.image_8 = toga.Image(src=self.result[7].get('thumbnail_content'))
        self.view_8 = toga.ImageView(self.image_8, style=Pack(width=200, height=140, padding=(0, 5, 0, 5)))
        self.button_name_8 = self.result[7].get("image_favorites") + "  " + self.result[7].get(
            'image_scale') + " " * 10 + self.result[7].get('name')

        self.image_9 = toga.Image(src=self.result[8].get('thumbnail_content'))
        self.view_9 = toga.ImageView(self.image_9, style=Pack(width=200, height=140, padding=(0, 5, 0, 5)))
        self.button_name_9 = self.result[8].get("image_favorites") + "  " + self.result[8].get(
            'image_scale') + " " * 10 + self.result[8].get('name')

        self.button_three_box = toga.Box(style=Pack(flex=1, direction=ROW, height=11, padding=(0, 5, 0, 5)))
        self.button_7 = toga.Button(self.button_name_7, on_press=self.view_details,
                                    style=Pack(background_color="rgb(204,229,255)", width=200, height=25,
                                               padding=(0, 5, 0, 5)))
        self.button_8 = toga.Button(self.button_name_8, on_press=self.view_details,
                                    style=Pack(background_color="rgb(204,229,255)", width=200, height=25,
                                               padding=(0, 5, 0, 5)))
        self.button_9 = toga.Button(self.button_name_9, on_press=self.view_details,
                                    style=Pack(background_color="rgb(204,229,255)", width=200, height=25,
                                               padding=(0, 5, 0, 5)))

        self.content_three_box.add(self.view_7)
        self.content_three_box.add(self.view_8)
        self.content_three_box.add(self.view_9)
        self.button_three_box.add(self.button_7)
        self.button_three_box.add(self.button_8)
        self.button_three_box.add(self.button_9)

        # 第四部分
        self.image_10 = toga.Image(src=self.result[9].get('thumbnail_content'))
        self.view_10 = toga.ImageView(self.image_10, style=Pack(width=200, height=140, padding=(0, 5, 0, 5)))
        self.button_name_10 = self.result[9].get("image_favorites") + "  " + self.result[9].get(
            'image_scale') + " " * 10 + self.result[9].get('name')

        self.image_11 = toga.Image(src=self.result[10].get('thumbnail_content'))
        self.view_11 = toga.ImageView(self.image_11, style=Pack(width=200, height=140, padding=(0, 5, 0, 5)))
        self.button_name_11 = self.result[10].get("image_favorites") + "  " + self.result[10].get(
            'image_scale') + " " * 10 + self.result[10].get('name')

        self.image_12 = toga.Image(src=self.result[11].get('thumbnail_content'))
        self.view_12 = toga.ImageView(self.image_12, style=Pack(width=200, height=140, padding=(0, 5, 0, 5)))
        self.button_name_12 = self.result[11].get("image_favorites") + "  " + self.result[11].get(
            'image_scale') + " " * 10 + self.result[11].get('name')

        self.button_four_box = toga.Box(style=Pack(flex=1, direction=ROW, height=11, padding=(0, 5, 0, 5)))
        self.button_10 = toga.Button(self.button_name_10, on_press=self.view_details,
                                     style=Pack(background_color="rgb(204,229,255)", width=200, height=25,
                                                padding=(0, 5, 0, 5)))
        self.button_11 = toga.Button(self.button_name_11, on_press=self.view_details,
                                     style=Pack(background_color="rgb(204,229,255)", width=200, height=25,
                                                padding=(0, 5, 0, 5)))
        self.button_12 = toga.Button(self.button_name_12, on_press=self.view_details,
                                     style=Pack(background_color="rgb(204,229,255)", width=200, height=25,
                                                padding=(0, 5, 0, 5)))

        self.content_four_box.add(self.view_10)
        self.content_four_box.add(self.view_11)
        self.content_four_box.add(self.view_12)
        self.button_four_box.add(self.button_10)
        self.button_four_box.add(self.button_11)
        self.button_four_box.add(self.button_12)

        # 底部区域 bottom padding=(上、右、下、左)
        bottom_box = toga.Box(style=Pack(flex=1, direction=ROW, padding=(25, 5, 5, 5)))

        # 上一页 下一页按钮
        self.page_one_bottom = toga.Button("上一页", on_press=self.previous_page,
                                           style=Pack(flex=1, font_weight="bold", direction=COLUMN,
                                                      background_color="blue",
                                                      padding=(5, 5, 5, 5), width=60, height=25))
        self.page_two_bottom = toga.Button("下一页", on_press=self.next_page,
                                           style=Pack(flex=1, font_weight="bold", direction=COLUMN,
                                                      background_color="blue",
                                                      padding=(5, 5, 5, 5), width=60, height=25))

        # 当前页
        self.page_text = toga.TextInput(value='第{}页'.format(self.page),
                                        style=Pack(flex=0, font_weight="bold", direction=ROW, padding=(5, 5, 5, 5),
                                                   width=60,
                                                   height=20),
                                        readonly=True)

        # 说明
        describe_lable = toga.Label("图片资源均来自网络，侵权请联系作者删除。QQ:2573514647",
                                    style=Pack(flex=1, direction=ROW, alignment=BOTTOM, text_align=CENTER,
                                               padding=(5, 5, 5, 5),
                                               width=400, height=20))

        bottom_box.add(self.page_text)
        bottom_box.add(describe_lable)
        bottom_box.add(self.page_one_bottom)
        bottom_box.add(self.page_two_bottom)

        # 注册头部
        self.main_box.add(title_box)

        # 注册内容的第一部分
        self.main_box.add(self.content_one_box)
        self.main_box.add(self.button_one_box)
        # 注册内容的第二部分
        self.main_box.add(self.content_two_box)
        self.main_box.add(self.button_two_box)
        # 注册内容的第三部分
        self.main_box.add(self.content_three_box)
        self.main_box.add(self.button_three_box)
        # 注册内容的第四部分
        self.main_box.add(self.content_four_box)
        self.main_box.add(self.button_four_box)
        # 注册底部
        self.main_box.add(bottom_box)
        # 数据加载完毕，显示页面
        self.main_window.content = self.main_box

    # 搜索按钮
    async def search(self, widget):
        # 设置进度条
        loading_box = toga.Box(style=Pack(direction=COLUMN, flex=1))
        progress = toga.ProgressBar(max=None)
        progress.start()
        loading_box.add(progress)
        self.main_window.content = loading_box
        # 获取用户输入的值
        self.search_value = self.search_input.value
        query = {"tag": self.search_value}

        # 设置搜索按钮的颜色以达到告知用户当前正在使用搜索的状态
        self.search_button.text = "✅"
        # 如果search_value 是空值，则表明用户退出搜索
        if self.search_value == '':
            # 展示没有搜索的内容 退出搜索还是有点问题
            # 进入搜索时是一种颜色 退出搜索时是白色
            self.search_button.text = "🔍"
            self.page = 1
            # 更新下一页的函数
            self.page_one_bottom.on_press = self.previous_page
            self.page_two_bottom.on_press = self.next_page
            await self.update()

        else:
            # 开始搜索
            result = []
            async for doc in async_collection_thumbnail.find(query).sort("_id", -1):
                result.append(doc)
            # 手动关闭MongoDB异步请求生命周期
            # client.close()
            result_total = len(result)
            if result_total == 0:
                await self.main_window.dialog(
                    toga.InfoDialog("⚠️", "没有搜索到标签为{}的图片，请换一个搜索词".format(self.search_value)))
                self.search_button.text = "🔍"
                self.page = 1
                self.main_window.content = self.main_box
            else:
                # 将结果返回到后续的页面上
                if (result_total // 12) != 0:
                    await self.main_window.dialog(toga.InfoDialog("☀️",
                                                                  "当前搜索词共得到标签为{}的壁纸{}页，请尽情挑选吧".format(
                                                                      self.search_value, (result_total // 12))))
                    self.search_page = 1
                    self.search_page_total = (result_total // 12)
                    # 展示搜索到的结果
                    self.progress.stop()
                    self.main_window.content = self.main_box
                    self.view_1.image = result[0].get('thumbnail_content')
                    self.button_1.text = result[0].get("image_favorites") + "  " + result[0].get(
                        'image_scale') + " " * 10 + result[0].get('name')
                    self.view_2.image = result[1].get('thumbnail_content')
                    self.button_2.text = result[1].get("image_favorites") + "  " + result[1].get(
                        'image_scale') + " " * 10 + result[1].get('name')
                    self.view_3.image = result[2].get('thumbnail_content')
                    self.button_3.text = result[2].get("image_favorites") + "  " + result[2].get(
                        'image_scale') + " " * 10 + result[2].get('name')
                    # 第二部分
                    self.view_4.image = result[3].get('thumbnail_content')
                    self.button_4.text = result[3].get("image_favorites") + "  " + result[3].get(
                        'image_scale') + " " * 10 + result[3].get('name')
                    self.view_5.image = result[4].get('thumbnail_content')
                    self.button_5.text = result[4].get("image_favorites") + "  " + result[4].get(
                        'image_scale') + " " * 10 + result[4].get('name')
                    self.view_6.image = result[5].get('thumbnail_content')
                    self.button_6.text = result[5].get("image_favorites") + "  " + result[5].get(
                        'image_scale') + " " * 10 + result[5].get('name')
                    # 第三部分
                    self.view_7.image = result[6].get('thumbnail_content')
                    self.button_7.text = result[6].get("image_favorites") + "  " + result[6].get(
                        'image_scale') + " " * 10 + result[6].get('name')
                    self.view_8.image = result[7].get('thumbnail_content')
                    self.button_8.text = result[7].get("image_favorites") + "  " + result[7].get(
                        'image_scale') + " " * 10 + result[7].get('name')
                    self.view_9.image = result[8].get('thumbnail_content')
                    self.button_9.text = result[8].get("image_favorites") + "  " + result[8].get(
                        'image_scale') + " " * 10 + result[8].get('name')
                    # 第四部分
                    self.view_10.image = result[9].get('thumbnail_content')
                    self.button_10.text = result[9].get("image_favorites") + "  " + result[9].get(
                        'image_scale') + " " * 10 + result[9].get('name')
                    self.view_11.image = result[10].get('thumbnail_content')
                    self.button_11.text = result[10].get("image_favorites") + "  " + result[10].get(
                        'image_scale') + " " * 10 + result[10].get('name')
                    self.view_12.image = result[11].get('thumbnail_content')
                    self.button_12.text = result[11].get("image_favorites") + "  " + result[11].get(
                        'image_scale') + " " * 10 + result[11].get('name')
                    # 页码进行更新
                    self.page_text.value = "第{}页".format(self.search_page)

                    # 更新下一页的函数
                    self.page_one_bottom.on_press = self.search_previous_page
                    self.page_two_bottom.on_press = self.search_next_page
                else:
                    await self.main_window.dialog(
                        toga.InfoDialog("☁️", "当前搜索词得到的壁纸数量太少，难以展示，请更换搜索词"))
                    self.search_button.text = "🔍"
                    self.page = 1
                    self.main_window.content = self.main_box

    # 上一页回调函数
    async def previous_page(self, widget):
        if self.page != 1:
            self.page -= 1
            await self.update()
        else:
            await self.main_window.dialog(toga.InfoDialog("⚠️", "已经是第一页了哦"))

    # 下一页回调函数
    async def next_page(self, widget):
        if self.page != self.image_total:
            self.page += 1
            await self.update()
        else:
            await self.main_window.dialog(toga.InfoDialog("⚠️", "地主家也没有余粮了"))

    # 搜索页面上一页
    async def search_previous_page(self, widget):
        if self.search_page != 1:
            self.search_page -= 1
            await self.search_update(value=self.search_value)
        else:
            await self.main_window.dialog(toga.InfoDialog("🔍️", "已经是搜索页面的第一页了哦😄"))

    # 搜索页面下一页
    async def search_next_page(self, widget):
        if self.search_page != self.search_page_total:
            self.search_page += 1
            await self.search_update(value=self.search_value)
        else:
            await self.main_window.dialog(toga.InfoDialog("🔍️", "已经是搜索页面的最后一页了😭"))

    async def search_update(self, value):
        # 设置加载页面
        self.progress.value = 1
        self.main_window.content = self.loading_box
        result = []
        async for doc in async_collection_thumbnail.find({'tag': value}).sort("_id", -1).skip(
                12 * (self.search_page - 1)).limit(
            12):
            result.append(doc)
            self.progress.value += 1

        # client.close()
        self.progress.stop()
        self.main_window.content = self.main_box

        self.view_1.image = result[0].get('thumbnail_content')
        self.button_1.text = result[0].get("image_favorites") + "  " + result[0].get('image_scale') + " " * 10 + result[
            0].get('name')
        self.view_2.image = result[1].get('thumbnail_content')
        self.button_2.text = result[1].get("image_favorites") + "  " + result[1].get('image_scale') + " " * 10 + result[
            1].get('name')
        self.view_3.image = result[2].get('thumbnail_content')
        self.button_3.text = result[2].get("image_favorites") + "  " + result[2].get('image_scale') + " " * 10 + result[
            2].get('name')
        # 第二部分
        self.view_4.image = result[3].get('thumbnail_content')
        self.button_4.text = result[3].get("image_favorites") + "  " + result[3].get('image_scale') + " " * 10 + result[
            3].get('name')
        self.view_5.image = result[4].get('thumbnail_content')
        self.button_5.text = result[4].get("image_favorites") + "  " + result[4].get('image_scale') + " " * 10 + result[
            4].get('name')
        self.view_6.image = result[5].get('thumbnail_content')
        self.button_6.text = result[5].get("image_favorites") + "  " + result[5].get('image_scale') + " " * 10 + result[
            5].get('name')
        # 第三部分
        self.view_7.image = result[6].get('thumbnail_content')
        self.button_7.text = result[6].get("image_favorites") + "  " + result[6].get('image_scale') + " " * 10 + result[
            6].get('name')
        self.view_8.image = result[7].get('thumbnail_content')
        self.button_8.text = result[7].get("image_favorites") + "  " + result[7].get('image_scale') + " " * 10 + result[
            7].get('name')
        self.view_9.image = result[8].get('thumbnail_content')
        self.button_9.text = result[8].get("image_favorites") + "  " + result[8].get('image_scale') + " " * 10 + result[
            8].get('name')
        # 第四部分
        self.view_10.image = result[9].get('thumbnail_content')
        self.button_10.text = result[9].get("image_favorites") + "  " + result[9].get('image_scale') + " " * 10 + \
                              result[9].get('name')
        self.view_11.image = result[10].get('thumbnail_content')
        self.button_11.text = result[10].get("image_favorites") + "  " + result[10].get('image_scale') + " " * 10 + \
                              result[10].get('name')
        self.view_12.image = result[11].get('thumbnail_content')
        self.button_12.text = result[11].get("image_favorites") + "  " + result[11].get('image_scale') + " " * 10 + \
                              result[11].get('name')
        # 页码进行更新
        self.page_text.value = "第{}页".format(self.search_page)

    async def update(self):
        # 设置加载中
        self.progress.value = 1
        self.main_window.content = self.loading_box
        result = []
        async for doc in async_collection_thumbnail.find({}).sort("_id", -1).skip(12 * (self.page - 1)).limit(12):
            result.append(doc)
            self.progress.value += 1

        # client.close()
        self.progress.stop()
        self.main_window.content = self.main_box

        self.view_1.image = result[0].get('thumbnail_content')
        self.button_1.text = result[0].get("image_favorites") + "  " + result[0].get('image_scale') + " " * 10 + result[
            0].get('name')
        self.view_2.image = result[1].get('thumbnail_content')
        self.button_2.text = result[1].get("image_favorites") + "  " + result[1].get('image_scale') + " " * 10 + result[
            1].get('name')
        self.view_3.image = result[2].get('thumbnail_content')
        self.button_3.text = result[2].get("image_favorites") + "  " + result[2].get('image_scale') + " " * 10 + result[
            2].get('name')
        # 第二部分
        self.view_4.image = result[3].get('thumbnail_content')
        self.button_4.text = result[3].get("image_favorites") + "  " + result[3].get('image_scale') + " " * 10 + result[
            3].get('name')
        self.view_5.image = result[4].get('thumbnail_content')
        self.button_5.text = result[4].get("image_favorites") + "  " + result[4].get('image_scale') + " " * 10 + result[
            4].get('name')
        self.view_6.image = result[5].get('thumbnail_content')
        self.button_6.text = result[5].get("image_favorites") + "  " + result[5].get('image_scale') + " " * 10 + result[
            5].get('name')
        # 第三部分
        self.view_7.image = result[6].get('thumbnail_content')
        self.button_7.text = result[6].get("image_favorites") + "  " + result[6].get('image_scale') + " " * 10 + result[
            6].get('name')
        self.view_8.image = result[7].get('thumbnail_content')
        self.button_8.text = result[7].get("image_favorites") + "  " + result[7].get('image_scale') + " " * 10 + result[
            7].get('name')
        self.view_9.image = result[8].get('thumbnail_content')
        self.button_9.text = result[8].get("image_favorites") + "  " + result[8].get('image_scale') + " " * 10 + result[
            8].get('name')
        # 第四部分
        self.view_10.image = result[9].get('thumbnail_content')
        self.button_10.text = result[9].get("image_favorites") + "  " + result[9].get('image_scale') + " " * 10 + \
                              result[9].get('name')
        self.view_11.image = result[10].get('thumbnail_content')
        self.button_11.text = result[10].get("image_favorites") + "  " + result[10].get('image_scale') + " " * 10 + \
                              result[10].get('name')
        self.view_12.image = result[11].get('thumbnail_content')
        self.button_12.text = result[11].get("image_favorites") + "  " + result[11].get('image_scale') + " " * 10 + \
                              result[11].get('name')
        # 页码进行更新
        self.page_text.value = "第{}页".format(self.page)

    def get_album_path(self):
        system = platform.system()
        if system == "Windows":
            return "Windows"
        elif system == "Linux":
            return "Linux"
        elif system == "Darwin":
            return "macOS"

    # 下载图片
    async def download_image(self, widget):
        image_name = widget.text.split(' ')[-1]
        # 设置进度条
        loading_box = toga.Box(style=Pack(direction=COLUMN, flex=1))
        progress = toga.ProgressBar(max=None)
        progress.start()
        loading_box.add(progress)
        self.main_window.content = loading_box
        res = await async_collection.find_one({"name": image_name})
        image_content = res.get('content')

        # 获取操作系统类型
        os_type = self.get_album_path()
        file_path = ''
        if os_type == 'macOS':
            # 创建存储图片的目录
            documents_dir = Path.home() / 'Desktop'
            images_dir = documents_dir / 'beewallpaper_images'
            images_dir.mkdir(parents=True, exist_ok=True)
            file_path = images_dir / image_name
            # 存储图片
            with open('{}'.format(file_path), 'wb') as file:
                file.write(image_content)
        elif os_type == "Windows":
            # C:\Users\Administrator\Desktop
            documents_dir = Path.home() / 'Desktop'
            images_dir = documents_dir / 'beewallpaper_images'
            images_dir.mkdir(parents=True, exist_ok=True)
            file_path = images_dir / image_name
            # 存储图片
            with open('{}'.format(file_path), 'wb') as file:
                file.write(image_content)

        self.main_window.content = self.main_box
        await self.main_window.dialog(toga.InfoDialog("👌", "{}下载完成,路径:{} ".format(image_name, file_path)))

    async def setting_wallpaper(self, widget):
        image_name = widget.text.split(' ')[-1]
        # 设置进度条
        loading_box = toga.Box(style=Pack(direction=COLUMN, flex=1))
        progress = toga.ProgressBar(max=None)
        progress.start()
        loading_box.add(progress)
        self.main_window.content = loading_box
        # res = await async_collection.find_one({"name": image_name})
        # image_content = res.get('content')

        # 获取操作系统类型
        os_type = self.get_album_path()
        file_path = ''
        if os_type == 'macOS':
            # 创建存储图片的目录
            documents_dir = Path.home() / 'Desktop'
            images_dir = documents_dir / 'beewallpaper_images'
            images_dir.mkdir(parents=True, exist_ok=True)
            file_path = images_dir / image_name
            # 判断是否存在壁纸，存在的话直接设置即可
            if not os.path.exists(file_path):
                # 通过image_name 下载图片内容然后再设置背景
                res = await async_collection.find_one({"name": image_name})
                image_content = res.get('content')
                # 存储图片
                with open('{}'.format(file_path), 'wb') as file:
                    file.write(image_content)
            # 设置为壁纸
            script = '''
            tell application "System Events"
                tell every desktop
                    set picture to POSIX file "{}"
                end tell
            end tell
            '''.format(file_path)
            result = subprocess.run(['osascript', '-e', script], capture_output=True, text=True)
            if result.returncode != 0:
                await self.main_window.dialog(toga.InfoDialog("⚠️", f"Error: {result.stderr}"))
            else:
                await self.main_window.dialog(toga.InfoDialog("⚠️", "设置成功"))

        elif os_type == "Windows":
            documents_dir = Path.home() / 'Desktop'
            images_dir = documents_dir / 'beewallpaper_images'
            images_dir.mkdir(parents=True, exist_ok=True)
            file_path = images_dir / image_name
            # 判断是否存在壁纸，不存在的话先下载
            if not os.path.exists(file_path):
                # 通过image_name 下载图片内容然后再设置背景
                res = await async_collection.find_one({"name": image_name})
                image_content = res.get('content')
                # 存储图片
                with open('{}'.format(file_path), 'wb') as file:
                    file.write(image_content)
            # 设置为壁纸
            image_path = os.path.abspath(file_path)
            image_path_w = ctypes.c_wchar_p(image_path)
            SPI_SETDESKWALLPAPER = 20
            ctypes.windll.user32.SystemParametersInfoW(SPI_SETDESKWALLPAPER, 0, image_path_w, 0)
            key = winreg.OpenKey(winreg.HKEY_CURRENT_USER, r"Control Panel\Desktop", 0, winreg.KEY_SET_VALUE)
            winreg.SetValueEx(key, "Wallpaper", 0, winreg.REG_SZ, image_path)
            winreg.CloseKey(key)
            await self.main_window.dialog(toga.InfoDialog("⚠️", "设置成功"))

        self.main_window.content = self.main_box
        # await self.main_window.dialog(toga.InfoDialog("👌", "{}下载完成,路径:{} ".format(image_name, file_path)))

    # 编写壁纸详情页
    async def view_details(self, widget):
        name = widget.text.split(' ')[-1]
        # print(name)
        # 主页面
        details_window = toga.Window(title="{}".format(name), closable=True, resizable=False)
        # 设置进度条
        loading_box = toga.Box(style=Pack(direction=COLUMN, flex=1))
        progress = toga.ProgressBar(max=None)
        progress.start()
        loading_box.add(progress)
        self.main_window.content = loading_box
        # res = []
        # async for doc in async_collection.find_one({"name": name}):
        #     res.append(doc)
        # result = res[0]
        # 获取壁纸信息
        thumbnail_result = await async_collection_thumbnail.find_one({"name": name})
        result = await async_collection.find_one({"name": name})

        # 设置进度条
        self.main_window.content = self.main_box
        progress.stop()
        # loading_box = toga.Box(style=Pack(direction=COLUMN, flex=1))
        # progress = toga.ProgressBar(max=None)
        # loading_box.add(progress)
        # progress.start()

        # details_window.content = loading_box
        # self.main_window.app.windows.add(details_window)
        # details_window.show()

        # 标签
        image_tag = thumbnail_result.get('tag')
        # 内容
        image_content = result.get('content')
        # 尺寸
        image_scale = thumbnail_result.get('image_scale')
        # 大小
        image_size = thumbnail_result.get('image_size')
        # 收藏数
        image_favorites = thumbnail_result.get('image_favorites')
        # 类型
        image_type = thumbnail_result.get('image_type')
        # 图片宽度
        image_width = int(thumbnail_result.get('image_width'))
        # 图片长度
        image_height = int(thumbnail_result.get('image_height'))
        if image_width > image_height:
            # 固定宽度
            width_num = 820
            proportion = image_width / image_height
            height_num = int(width_num / proportion)
            # print("固定宽度：820 长度:{}".format(height_num))
        else:
            # 固定高度
            height_num = 700
            proportion = image_height / image_width
            width_num = int(height_num / proportion)
            # width_num = 720
            # print("固定高度：820 宽度：{}".format(width_num))

        # 壁纸
        details_content_box = toga.Box(style=Pack(direction=COLUMN, flex=1, alignment=CENTER, padding=(0, 0, 0, 0)))
        details_image = toga.Image(src=image_content)
        # 计算尺寸大小 等比缩放 缩小五倍
        """
         # 计算方式：
            1、2560 / 1440 获取比例
            2、固定width = 820
            3、 height = 820 除以 比例
        """

        details_image_view = toga.ImageView(details_image,
                                            style=Pack(direction=COLUMN, flex=1, width=width_num, height=height_num,
                                                       alignment=CENTER,
                                                       padding=(0, 0, 10, 0)))
        details_content_box.add(details_image_view)

        # 底部元素：1、标签 选择框 2、底部居中：尺寸、大小、收藏数 3、下载 、 取消
        details_bottom_box = toga.Box(style=Pack(direction=ROW, flex=0, padding=(0, 0, 10, 0)))
        # padding=(上、右、下、左)
        details_tag_lable = toga.Label(text='标签:', style=Pack(direction=ROW, flex=0, width=40, padding=(0, 0, 0, 20)))
        details_selection = toga.Selection(items=image_tag, style=Pack(flex=0, padding=(0, 20, 0, 0)))
        details_selection.value = image_tag[0]
        details_bottom_lable = toga.Label(
            text='尺寸:{} | 大小:{} | 收藏:{}'.format(image_scale, image_size, image_favorites),
            style=Pack(direction=ROW, alignment=CENTER, flex=0, padding=(0, 0, 0, 20)))
        details_download = toga.Button("下载" + " " * 10 + name, on_press=self.download_image,
                                       style=Pack(flex=0, background_color="green", width=50, padding=(0, 0, 0, 20)))
        setting_wallpaper = toga.Button("设置" + " " * 10 + name, on_press=self.setting_wallpaper,
                                        style=Pack(flex=0, background_color="green", width=50, padding=(0, 30, 0, 20)))

        details_bottom_box.add(details_tag_lable)
        details_bottom_box.add(details_selection)
        details_bottom_box.add(details_bottom_lable)
        details_bottom_box.add(details_download)
        details_bottom_box.add(setting_wallpaper)

        # 将底部控件加入到壁纸所在的box中
        details_content_box.add(details_bottom_box)

        # 弹框展示内容
        details_window.content = details_content_box
        self.main_window.app.windows.add(details_window)
        details_window.show()


def main():
    return BeeWallpaper()